
package com.gzbsoft.sc.modules.sys.service.impl;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.gzbsoft.sc.common.exception.RRException;
import com.gzbsoft.sc.modules.sys.dao.SysCaptchaDao;
import com.gzbsoft.sc.modules.sys.entity.SysCaptcha;
import com.gzbsoft.sc.modules.sys.service.SysCaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.Date;
/**
 * 验证码
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysCaptchaService")
public class SysCaptchaServiceImpl extends BaseServiceImpl<SysCaptcha, Long> implements SysCaptchaService {
    @Autowired
    private SysCaptchaDao sysCaptchaDao;
    @Override
    public Image getCaptcha(String uuid) {
        if (StrUtil.isBlank(uuid)) {
            throw new RRException("uuid不能为空");
        }
        //生成文字验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        String code = lineCaptcha.getCode();
        SysCaptcha captchaEntity = new SysCaptcha();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(DateUtil.offsetMinute(new Date(), 5));
        sysCaptchaDao.save(captchaEntity);
        return lineCaptcha.createImage(code);
    }
    @Override
    public boolean validate(String uuid, String code) {
        SysCaptcha captchaEntity = sysCaptchaDao.findByProperty("uuid", uuid).orElse(null);
        if (captchaEntity == null) {
            return false;
        }
        //删除验证码
        sysCaptchaDao.delete(SysCaptcha.builder().uuid(uuid).build());
        if (captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()) {
            return true;
        }
        return false;
    }
}
